package cn.tedu.charging.order.config;

import cn.tedu.charging.order.emqx.MqttCallback;
import cn.tedu.charging.order.emqx.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MqttClientConfig {
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;

    private MqttContext mqttContext;
    @Autowired
    public void setMqttContext(MqttContext mqttContext) {
        this.mqttContext = mqttContext;
    }

    @Bean
    public MqttClient mqttClientInit() {
        MqttClient mqttClient = null;
        try {
            mqttClient = new MqttClient(address, UUID.randomUUID().toString(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            mqttClient.setCallback(new MqttCallback(mqttClient, mqttContext));
            mqttClient.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mqttClient;
    }
}
